using AutoMapper;
using MediatR;
using RBAC.Domain.Approval;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Approval;

namespace RBAC.Write.Api.Application.Handler.Approval
{
    /// <summary>
    /// 更新审批流程处理器
    /// </summary>
    public class UpdateApprovalProcessHandler : IRequestHandler<UpdateApprovalProcessCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ApprovalProcess> approvalProcessRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateApprovalProcessHandler> logger;

        public UpdateApprovalProcessHandler(
            IBaseRepository<ApprovalProcess> approvalProcessRepository,
            IMapper mapper,
            ILogger<UpdateApprovalProcessHandler> logger)
        {
            this.approvalProcessRepository = approvalProcessRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 处理更新审批流程命令
        /// </summary>
        /// <param name="request">更新审批流程命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        public async Task<APIResult<int>> Handle(UpdateApprovalProcessCommand request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始更新审批流程，ID: {Id}", request.Id);

                // 查找现有的审批流程（排除已删除的）
                var existingProcess = approvalProcessRepository.GetALL()
                    .FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);

                if (existingProcess == null)
                {
                    logger.LogWarning("未找到审批流程，ID: {Id}", request.Id);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "未找到指定的审批流程",
                        Data = 0
                    };
                }

                // 检查流程名称是否重复（排除当前流程和已删除的流程）
                var duplicateProcess = approvalProcessRepository.GetALL()
                    .FirstOrDefault(x => x.ProcessName == request.ProcessName && x.Id != request.Id && !x.IsDeleted);

                if (duplicateProcess != null)
                {
                    logger.LogWarning("审批流程名称已存在: {ProcessName}", request.ProcessName);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "审批流程名称已存在",
                        Data = 0
                    };
                }

                // 更新流程信息
                existingProcess.ProcessName = request.ProcessName;
                existingProcess.Description = request.ProcessDescription;
                existingProcess.ProcessType = request.ProcessType;
                existingProcess.Status = request.IsEnabled ? 1 : 0;
                existingProcess.CreateUser = request.UpdateUser ?? "系统";

                // 执行更新
                var result = approvalProcessRepository.Update(existingProcess);

                if (result > 0)
                {
                    logger.LogInformation("审批流程更新成功，ID: {Id}", request.Id);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Success,
                        Msg = "审批流程更新成功",
                        Data = result
                    };
                }
                else
                {
                    logger.LogError("审批流程更新失败，ID: {Id}", request.Id);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "审批流程更新失败",
                        Data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新审批流程时发生异常，ID: {Id}", request.Id);
                return new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = $"更新审批流程失败：{ex.Message}",
                    Data = 0
                };
            }
        }
    }
}
